import axios, { AxiosHeaders } from "axios";
import { ElMessage } from "element-plus";
import { useGlobalStore } from "@/stores/modules/global";
import UserStore from "@/stores/modules/user";
import router from "@/routers";

import { addPending, removePending } from "./pendingManager";
import { handleResponseError, getCodeMessage } from "./errorHandler";

const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL || "/api",
  timeout: 10000
});

service.interceptors.request.use(config => {
  if (!config.signal) {
    addPending(config);
  }

  const userStore = UserStore();
  const globalStore = useGlobalStore();
  const getToken = config.customOptions?.getToken || (() => userStore.token);
  const token = getToken();

  if (token) {
    config.headers = new AxiosHeaders({
      ...config.headers,
      Authorization: `${token}`,
      Lang: globalStore.locale
    });
  }

  return config;
});

service.interceptors.response.use(
  response => {
    removePending(response.config);

    const userStore = UserStore();

    if (response.headers.RefreshToken) {
      userStore.setToken(response.headers.RefreshToken);
    }

    if (response.data.code === 401) {
      ElMessage.error(response.data.message || getCodeMessage(401));
      userStore.clearUserInfo();
      router.replace("/login");
      return Promise.reject(response.data);
    }

    if (response.data.code && response.data.code !== 20000) {
      ElMessage.error(response.data.message || getCodeMessage(response.data.code));
      return Promise.reject(response.data);
    }

    return response.data;
  },
  error => {
    if (axios.isCancel(error)) {
      return Promise.reject(new Error("请求已取消"));
    }
    return handleResponseError(error);
  }
);

export default service;
